<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" v-auth="'categories:blog_categories:add'" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button
          type="primary"
          v-auth="'categories:blog_categories:edit'"
          @click="handleUpdateAllArticleCounts"
          preIcon="ant-design:reload-outlined"
          :loading="updateLoading"
        >
          更新文章数量
        </a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button v-auth="'categories:blog_categories:deleteBatch'"
            >批量操作
            <Icon icon="mdi:chevron-down" />
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record }">
        <!-- 颜色列插槽 -->
        <template v-if="column.dataIndex === 'color'">
          <span class="color-dot" :style="{ background: record.color }" v-if="record.color"></span>
        </template>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <BlogCategoriesModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="categories-blogCategories" setup>
  import { ref, reactive } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import BlogCategoriesModal from './components/BlogCategoriesModal.vue';
  import { columns, searchFormSchema, superQuerySchema } from './BlogCategories.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, saveOrUpdate, recalculateArticleCounts } from './BlogCategories.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  import { message } from 'ant-design-vue';
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  //注册model
  const [registerModal, { openModal }] = useModal();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: 'blog_categories',
      api: list,
      columns,
      canResize: false,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: 'blog_categories',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
  /**
   * 新增事件
   */
  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    const actions = [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        auth: 'categories:blog_categories:edit',
      },
    ];

    // 根据状态显示不同的操作
    if (record.status === 1) {
      // 启用状态：显示禁用按钮
      actions.push({
        label: '禁用',
        popConfirm: {
          title: '是否确认禁用该分类？',
          confirm: () => handleStatusChange(record, 0),
          placement: 'topLeft',
        },
        auth: 'categories:blog_categories:edit',
      });
    } else {
      // 禁用状态：显示启用按钮
      actions.push({
        label: '启用',
        popConfirm: {
          title: '是否确认启用该分类？',
          confirm: () => handleStatusChange(record, 1),
          placement: 'topLeft',
        },
        auth: 'categories:blog_categories:edit',
      });
    }

    return actions;
  }

  /**
   * 状态变更事件
   */
  async function handleStatusChange(record, newStatus) {
    try {
      const updateData = {
        ...record,
        status: newStatus,
      };
      await saveOrUpdate(updateData, true);
      message.success(newStatus === 1 ? '启用成功' : '禁用成功');
      reload();
    } catch (error) {
      console.error('状态变更失败:', error);
      message.error('状态变更失败');
    }
  }

  const updateLoading = ref(false);

  async function handleUpdateAllArticleCounts() {
    try {
      updateLoading.value = true;
      // 调用重新计算所有分类文章数量的接口
      await recalculateArticleCounts();
      message.success('更新文章数量成功');
      reload();
    } catch (error) {
      console.error('更新文章数量失败:', error);
      message.error('更新文章数量失败');
    } finally {
      updateLoading.value = false;
    }
  }
</script>

<style lang="less" scoped>
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }

  // 颜色显示样式
  .color-display {
    display: flex;
    align-items: center;
    gap: 8px;
    justify-content: center;

    .color-block {
      width: 20px;
      height: 20px;
      border-radius: 4px;
      border: 1px solid #d9d9d9;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    }

    .color-text {
      font-size: 12px;
      color: #666;
      max-width: 80px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .no-color {
    color: #999;
    font-size: 12px;
  }

  .color-dot {
    display: inline-block;
    width: 28px;
    height: 18px;
    border-radius: 8px;
    vertical-align: middle;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    border: 1px solid #eee;
  }
</style>
